package com.dalin.demo.controller;

import com.dalin.demo.pojo.entity.*;
import com.dalin.demo.pojo.entity.Class;
import com.dalin.demo.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/classes")
@CrossOrigin(origins = "*")
public class ClassController {

    @Autowired
    private ClassService classService;

    @PostMapping("/list")
    public List<Class> listClass(@RequestParam Map<String, Object> params) {
        System.out.println("getAllClass by params==="+ params);
        return classService.listClassByParams(params);
    }

    @PostMapping("/add")
    public Class addClass(@RequestBody Class class1) throws Exception {
        System.out.println("addStudent===" + class1);
        classService.addClass(class1);
        return class1;
    }

    @PostMapping("/edit")
    public String updateClass(@RequestBody Class class1) throws Exception {
        System.out.println("updateClass===" + class1);
        classService.updateClass(class1);
        return "success";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteClass(@PathVariable Integer id) {
        System.out.println("deleteClass by id==="+ id);
        classService.deleteClass(id);
        return "success";
    }

    @PostMapping("/enrollClass")
    public ResponseEntity<?> enrollStudentsToCourse(@RequestBody EnrollClassesRequest request) {
        try {
            List<StudentClass> studentClasses = request.getStudentIds().stream()
                    .map(studentId -> new StudentClass(studentId,request.getClassId()))
                    .collect(Collectors.toList());

            classService.batchAddClass(studentClasses);
            return ResponseEntity.ok("Students successfully enrolled to the course");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error enrolling students to the course");
        }
    }

    @GetMapping("/enrolledStudents/{classId}")
    public ResponseEntity<?> getEnrolledStudents(@PathVariable Long classId) {
        try {
            List<StudentClass> enrolledStudents = classService.getEnrolledStudentsByCourseId(classId);
            System.out.println(enrolledStudents);
            return ResponseEntity.ok(enrolledStudents);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving enrolled students");
        }
    }

    @DeleteMapping("/deleteStu/{id}")
    public String deleteStudent(@PathVariable Integer id) {
        System.out.println("deleteStudent by id==="+ id);
        classService.deleteStudent(id);
        return "success";
    }
}